import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/dashboard'
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue'),
      meta: { title: '登录' }
    },
    {
      path: '/register',
      name: 'register',
      component: () => import('../views/RegisterView.vue'),
      meta: { title: '注册' }
    },
    {
      path: '/dashboard',
      name: 'dashboard',
      component: () => import('../views/DashboardView.vue'),
      meta: { title: '患者概述', requiresAuth: true }
    },
    {
      path: '/diagnosis',
      name: 'diagnosis',
      component: () => import('../views/DiagnosisView.vue'),
      meta: { title: '诊断与治疗计划', requiresAuth: true }
    },
    {
      path: '/living-will',
      name: 'living-will',
      component: () => import('../views/LivingWillView.vue'),
      meta: { title: '医嘱管理', requiresAuth: true }
    },
    {
      path: '/medical-records',
      name: 'medical-records',
      component: () => import('../views/MedicalRecordsView.vue'),
      meta: { title: '病情记录', requiresAuth: true }
    },
    {
      path: '/profile',
      name: 'profile',
      component: () => import('../views/ProfileView.vue'),
      meta: { title: '个人中心', requiresAuth: true }
    },
    {
      path: '/404',
      name: 'not-found',
      component: () => import('../views/NotFoundView.vue'),
      meta: { title: '页面不存在' }
    },
    {
      path: '/:pathMatch(.*)*',
      redirect: '/404'
    }
  ]
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `${to.meta.title} - 康养中心患者监护系统` : '康养中心患者监护系统'
  
  // 获取用户状态
  const userStore = useUserStore()
  
  // 检查是否需要登录权限
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 使用pinia中的isLoggedIn判断是否已登录
    if (!userStore.isLoggedIn) {
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      next()
    }
  } else if (to.path === '/login' || to.path === '/register') {
    // 如果已登录且访问登录或注册页面，则重定向到首页
    if (userStore.isLoggedIn) {
      next({ path: '/dashboard' })
    } else {
      next()
    }
  } else if (to.path === '/404') {
    // 如果已登录且访问404页面，根据来源页面决定去向
    if (userStore.isLoggedIn) {
      // 如果是从登录页过来的，则重定向到首页
      if (from.path === '/login') {
        next({ path: '/dashboard' })
      } else {
        next()
      }
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
